package com.hzbank.juc.synWait;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description:
 * @author: libugu@cskaoyan.com
 * @date 2023/12/25 - 19:04
 */
@Slf4j
public class SyncWaitNotify02 extends ReentrantLock {
    private int loop;
    public SyncWaitNotify02(int loop){
        this.loop = loop;
    }

    public void print(String print, Condition current,Condition next){
        for (int i = 0; i < loop; i++) {

            lock();
            try {
                current.await();
                log.debug(print);
                next.signal();

            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                unlock();
            }
        }

    }


    public static void main(String[] args) throws InterruptedException {
        SyncWaitNotify02 awaitSignal = new SyncWaitNotify02(5);
        Condition a = awaitSignal.newCondition();
        Condition b = awaitSignal.newCondition();
        Condition c = awaitSignal.newCondition();

        new Thread(() -> {
            awaitSignal.print("a", a, b);
        }).start();

        new Thread(() -> {
            awaitSignal.print("b", b, c);
        }).start();

        new Thread(() -> {
            awaitSignal.print("c", c, a);
        }).start();

        Thread.sleep(1000);

        awaitSignal.lock();
        try {
            System.out.println("开始...");
            a.signal();
        } finally {
            awaitSignal.unlock();
        }
    }

}
